import { ref, onMounted, onUnmounted } from "vue";

/**
 * CSS变量操作 Hook
 * @param varName CSS变量名
 * @param defaultValue 默认值
 * @returns [value, setValue] - 返回当前值和设置值的函数
 */
export function useCssVar<T extends string | number>(
  varName: string,
  defaultValue: T
) {
  const value = ref(defaultValue);

  // 获取CSS变量值
  const getValue = () => {
    return typeof defaultValue === "number"
      ? parseInt(
          getComputedStyle(document.documentElement).getPropertyValue(varName)
        ) || defaultValue
      : getComputedStyle(document.documentElement)
          .getPropertyValue(varName)
          .trim() || defaultValue;
  };

  // 设置CSS变量值
  const setValue = (newValue: T) => {
    document.documentElement.style.setProperty(
      varName,
      typeof newValue === "number" ? `${newValue}px` : newValue
    );
    value.value = newValue;
  };

  // 监听其他地方对CSS变量的修改
  let observer: MutationObserver;

  onMounted(() => {
    value.value = getValue();

    observer = new MutationObserver(() => {
      const newValue = getValue();
      if (newValue !== value.value) {
        value.value = newValue;
      }
    });

    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ["style"],
    });
  });

  onUnmounted(() => {
    observer?.disconnect();
  });

  return {
    value,
    setValue,
  };
}
